package com.wyl.learn01;

import cn.hutool.core.util.RandomUtil;
import com.rabbitmq.client.*;
import com.wyl.config.RabbitMqConfig;


public class Consumer01 {
    private final static String QUEUE_NAME = "hello";

    public static void main(String[] args) throws Exception {
        System.out.println("我是消费者：" + RandomUtil.randomString(RandomUtil.BASE_CHAR, 2));
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(RabbitMqConfig.IP);
        factory.setUsername(RabbitMqConfig.USERNAME);
        factory.setPassword(RabbitMqConfig.PASSWORD);

        // 这里不能用try-resource，因为执行完会自动关闭。这里要一直监听消息
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        System.out.println("等待接收消息.........");
        // 消费者接收消息的回调
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody());
            System.out.println("接收到消息：" + message);
        };
        // 消费者取消消费消息的回调，如在消费的时候队列被删除掉了
        CancelCallback cancelCallback = (consumerTag) -> {
            System.out.println("消息消费被中断");
        };
        /**
         * 消费者消费消息
         * 1.消费哪个队列
         * 2.消费成功之后是否要自动应答 true 代表自动应答 false 手动应答
         * 3.消费者接收消息的回调
         * 4.消费者取消消费消息的回调
         */
        channel.basicConsume(QUEUE_NAME, true, deliverCallback, cancelCallback);
    }
}
